// 用户登录状态管理
let userLoggedIn = false;
let currentUser = null;

// API配置
const API_CONFIG = {
    BASE_URL: 'http://localhost:8080',
    LOGIN_ENDPOINT: '/api/auth/login',
    REGISTER_ENDPOINT: '/api/auth/register'
};

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 检查登录状态
    checkLoginStatus();
});

// 检查登录状态
function checkLoginStatus() {
    // 从localStorage获取登录状态
    const isLoggedIn = localStorage.getItem('userLoggedIn') === 'true';
    const userEmail = localStorage.getItem('userEmail');
    const userType = localStorage.getItem('userType');

    if (isLoggedIn && userEmail) {
        userLoggedIn = true;
        currentUser = {
            username: userEmail,
            email: userEmail,
            type: userType,
            avatar: `https://picsum.photos/id/${Math.floor(Math.random() * 1000)}/40/40`
        };
    } else {
        userLoggedIn = false;
        currentUser = null;
    }

    // 更新UI
    updateUserInterface();
}

// 更新用户界面
function updateUserInterface() {
    const userAvatar = document.getElementById('userAvatar');

    if (userLoggedIn && currentUser) {
        // 登录状态：显示用户头像
        if (userAvatar) {
            userAvatar.src = currentUser.avatar;
        }
    } else {
        // 未登录状态：显示默认灰色头像
        if (userAvatar) {
            userAvatar.src = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='40' height='40' viewBox='0 0 24 24' fill='none' stroke='%23ccc' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2'%3E%3C/path%3E%3Ccircle cx='12' cy='7' r='4'%3E%3C/circle%3E%3C/svg%3E";
        }
    }
}

// 通用API请求函数
async function apiRequest(url, options = {}) {
    try {
        const response = await fetch(url, {
            headers: {
                'Content-Type': 'application/json',
                ...options.headers
            },
            ...options
        });

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        const data = await response.json();
        return { success: true, data };
    } catch (error) {
        console.error('API请求错误:', error);
        return {
            success: false,
            error: error.message || '网络请求失败，请稍后重试'
        };
    }
}

// 显示消息
function showMessage(message, type = 'info') {
    const messageContainer = document.getElementById('message-container');
    if (!messageContainer) return;

    // 清除现有消息
    messageContainer.innerHTML = '';

    const messageDiv = document.createElement('div');
    messageDiv.className = `alert alert-${type} auto-hide`;
    messageDiv.textContent = message;

    messageContainer.appendChild(messageDiv);

    // 5秒后自动隐藏
    setTimeout(() => {
        messageDiv.style.opacity = '0';
        setTimeout(() => {
            if (messageDiv.parentNode) {
                messageDiv.parentNode.removeChild(messageDiv);
            }
        }, 500);
    }, 5000);
}

// 设置按钮加载状态
function setLoading(button, isLoading) {
    if (isLoading) {
        button.disabled = true;
        const originalText = button.textContent;
        button.dataset.originalText = originalText;
        button.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 处理中...';
    } else {
        button.disabled = false;
        const originalText = button.dataset.originalText;
        button.textContent = originalText || button.textContent;
    }
}

// 清除表单错误状态
function clearFormErrors() {
    const errorMessages = document.querySelectorAll('.error-message');
    errorMessages.forEach(error => {
        error.style.display = 'none';
        error.style.opacity = '0';
    });

    const formGroups = document.querySelectorAll('.form-group');
    formGroups.forEach(group => {
        group.classList.remove('has-error');
    });
}

// 显示字段错误
function showFieldError(inputElement, errorElementId, message) {
    const errorElement = document.getElementById(errorElementId);
    if (!errorElement) return;

    const formGroup = inputElement.parentNode.parentNode;
    formGroup.classList.add('has-error');
    errorElement.textContent = message;
    errorElement.style.display = 'block';
    errorElement.style.opacity = '1';

    // 5秒后自动隐藏
    setTimeout(() => {
        if (errorElement.style.display === 'block') {
            hideFieldError(inputElement, errorElementId);
        }
    }, 5000);
}

// 隐藏字段错误
function hideFieldError(inputElement, errorElementId) {
    const errorElement = document.getElementById(errorElementId);
    if (!errorElement) return;

    const formGroup = inputElement.parentNode.parentNode;
    formGroup.classList.remove('has-error');
    errorElement.style.opacity = '0';
    setTimeout(() => {
        errorElement.style.display = 'none';
    }, 300);
}

// 验证邮箱格式
function validateEmail(email) {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
}

// 验证密码长度
function validatePassword(password) {
    return password.length >= 6 && password.length <= 20;
}